package com.css.common.core.utils;

import com.css.common.core.constent.CommonConstant;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serializable;

/**
 * R
 * 响应信息
 *
 * @author hanyx
 * @date 2019/05/02
 */
@ToString
@Accessors(chain = true)
public class R<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    @Getter
    @Setter
    private int code = CommonConstant.SUCCESS;

    @Getter
    @Setter
    private String msg = "success";

    @Getter
    @Setter
    private T data;

    @Getter
    private String reqId = SessionIdHolder.get();

    public R() {
        super();
    }

    public R(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public R(T data) {
        super();
        this.data = data;
    }

    public R(T data, String msg) {
        super();
        this.data = data;
        this.msg = msg;
    }

    public R(Throwable e) {
        super();
        this.msg = e.getMessage();
        this.code = CommonConstant.FAIL;
    }

    public R(Throwable e, int code) {
        super();
        this.msg = e.getMessage();
        this.code = code;
    }

    public R(String msg, int code) {
        this.msg = msg;
        this.code = code;
    }

    public static R buildError(String msg) {
        return R.builder().code(CommonConstant.FAIL).data(Boolean.FALSE).msg(msg).build();
    }

    public static R buildError(String msg, int code) {
        return R.builder().code(code).data(Boolean.FALSE).msg(msg).build();
    }

    public static R buildError(Throwable e) {
        String msg = e.getMessage();
        return buildError(msg);
    }

    public static <T> R buildSuccess(T data) {
        return R.builder().code(CommonConstant.SUCCESS).data(data).msg("success").build();
    }

    public static <T> R.RBuilder<T> builder() {
        return new R.RBuilder();
    }

    public static class RBuilder<T> {
        private int code = CommonConstant.SUCCESS;
        private String msg = "success";
        private T data;
        private String reqId = SessionIdHolder.get();

        RBuilder() {
        }

        public R.RBuilder<T> code(int code) {
            this.code = code;
            return this;
        }

        public R.RBuilder<T> msg(String msg) {
            this.msg = msg;
            return this;
        }

        public R.RBuilder<T> data(T data) {
            this.data = data;
            return this;
        }

        public R<T> build() {
            return new R(this.code, this.msg, this.data);
        }

        public String toString() {
            return "R.RBuilder(code=" + this.code + ", msg=" + this.msg + ", data=" + this.data + ")";
        }
    }
}
